package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketRole;
import com.cskaoyan.market.db.domain.MarketRoleExample;
import com.cskaoyan.market.db.mapper.MarketRoleMapper;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.MybatisUtils;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.vo.MarketRoleVo;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/admin/role/*")
public class AdminRoleController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/role/", "");
        if ("options".equals(op)) {
            options(req, resp);
        }
    }

    private void options(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        SqlSession session = MybatisUtils.getSession();
        MarketRoleMapper mapper = session.getMapper(MarketRoleMapper.class);
        MarketRoleExample marketRoleExample = new MarketRoleExample();
        List<MarketRole> marketRoles = mapper.selectByExample(marketRoleExample);
        session.commit();
        session.close();
        List<MarketRoleVo> marketRoleVoList = new ArrayList<>();
        for (MarketRole marketRole : marketRoles) {
            marketRoleVoList.add(new MarketRoleVo(marketRole.getName(),marketRole.getId()));
        }
        Object o = ResponseUtil.okList(marketRoleVoList);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
    }
}
